#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# xhs_search_dropdown.py

"""
单一笔记爬虫
使用Playwright自动获取单一笔记信息
"""

import os
import sys
import re

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(current_dir))

# 初始化playwright配置
from playwright.sync_api import sync_playwright
from xhs_note_info.note_info_get import get_element_1, get_last_update_time, get_three_data, get_ip_location, get_note_author_info
from config import AUTH_FILE, Config

# URL
note_info_dict = {}

def main(html_url = 'https://www.xiaohongshu.com/explore/67cb304f000000000703558c?xsec_token=AB20d7TdpHsAJVKViN47LJMDs32YEyqOH_iRMjGStU9AU=&xsec_source=pc_search&source=unknown'):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=Config.IF_HEADLESS)
        context = browser.new_context(storage_state=AUTH_FILE if os.path.exists(AUTH_FILE) else None)  
        page = context.new_page()

        # 跳转至落地页
        page.goto(html_url, wait_until='networkidle')

        # 保存页面源码到文件
        html_content = page.content()

        # 博主url
        note_info_dict['note_url'] = html_url

        # 笔记标题
        note_title = re.sub(" - 小红书", "", get_element_1(html_content, 'og:title'))
        note_info_dict['note_title'] = note_title

        # 笔记内容
        note_content = get_element_1(html_content, 'description')
        note_info_dict['note_content'] = note_content

        # 笔记日期
        note_time = get_last_update_time(html_content)
        note_info_dict['note_time'] = note_time

        # 笔记点赞，评论，收藏
        note_data = get_three_data(html_content)
        note_info_dict['note_like_num'] = note_data[0]
        note_info_dict['note_collect_num'] = note_data[1]
        note_info_dict['note_comment_num'] = note_data[2]
        note_info_dict['note_share_num'] = note_data[3]

        # 关联话题
        note_topic = get_element_1(html_content, 'keywords')
        note_info_dict['note_topic'] = note_topic

        # 发布地点
        note_ip = get_ip_location(html_content)
        note_info_dict['note_ip'] = note_ip

        # 内容类型
        note_type = get_element_1(html_content, 'og:type')
        note_info_dict['note_type'] = note_type

        # 作者名字, 作者url
        blogger_info = get_note_author_info(html_content)
        note_info_dict['blogger_name'] = blogger_info[0]
        note_info_dict['blogger_url'] = blogger_info[1]

        print(note_info_dict)

        # 保存登录状态
        context.storage_state(path=AUTH_FILE)
        browser.close()
    return note_info_dict

if __name__ == "__main__":
    main('https://www.xiaohongshu.com/explore/67d016070000000029038f20?xsec_token=ABjPdqAPWHilBa5mk9FrKzD3Pn4gw89ajGNf9Vcsk6cHc=&xsec_source=pc_feed')